const express = require('express')
const router = express.Router()
const {query} = require('../../db')
const jwt = require('jsonwebtoken')
const config = require('../../config')
const md5 = require('md5')

router.post('/', async (req, res, next)=>{
    
    // 1. 接收参数
    let account = req.body.account
    let password = req.body.password

    // 2. 使用账号查询数据库看有没有
    let sql = 'SELECT id,password FROM admins WHERE account=?'
    let ret = await query(sql, [account]).catch(next)
    if(ret === undefined) return 

    if(ret.length === 0) return next('账号不存在')

    // 判断密码
    if(ret[0].password === md5(password + config.admin_key) ) {
        // 生成令牌
        let token = jwt.sign({id: ret[0].id}, config.admin_key)
        res.json({
            'ok': 1,
            'data': {
                token
            }
        })
    } else
        next('密码错误！')

})


// 导出这个文件路由
module.exports = router